import { Effect, Reducer } from 'umi';
import { message } from "antd";
import { addProject, saveUnit, queryProject, removeProject, updateProject } from './service';

import { ProjectListItem } from './data.d';

export interface StateType {
  list: ProjectListItem[];
}

export interface ModelType {
  namespace: string;
  state: StateType;
  effects: {
    fetch: Effect;
    add: Effect;
    update: Effect;
    remove: Effect;
    unitSave: Effect;
  };
  reducers: {
    save: Reducer<StateType>;
  };
}

const Model: ModelType = {
  namespace: 'projectList',

  state: {
    list: [],
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const response = yield call(queryProject, payload);
      yield put({
        type: 'save',
        payload: Array.isArray(response) ? response : [],
      });
    },
    *add({ payload }, { call, put }) {
      const response = yield call(addProject, payload);
      yield put({
        type: 'save',
        payload: Array.isArray(response) ? response : [],
      });
    },
    *update({ payload }, { call, put }) {
      const response = yield call(updateProject, payload); // post
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *remove({ payload }, { call, put }) {
      const response = yield call(removeProject, payload); // post
      yield put({
        type: 'save',
        payload: response,
      });
    },
    *unitSave({ payload, callback }, { call }) {
      const response = yield call(saveUnit, payload);
      if (response && response.code === 0) {
        message.success('操作成功');
        if (callback) {
          callback(true);
        }
      } else {
        message.success('操作失败');
        if (callback) {
          callback(false);
        }
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
  },
};

export default Model;
